package com.zhangmeng.tools.editors.codemirr;

import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ClipboardUtils;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @author zhangmeng
 * @date 2023年10月9日09:06:29
 * @version 1.0
 *
 */
@Slf4j
public class CodeMirrWebView extends AnchorPane {

    public SimpleStringProperty text_code = new SimpleStringProperty("");

    public void setText(String text){
        log.info("text:" + text);
        text_code.setValue(text);
    }

    private JSObject window;

    public CodeMirrWebView() {
        init();
    }

    private File file;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public WebView getView() {
        return view;
    }

    public void setView(WebView view) {
        this.view = view;
    }

    private WebView view = new WebView();

    public void init() {

        WebEngine engine = view.getEngine();

        String url = this.getClass().getResource("/static/editors/code-mirror.html").toExternalForm();

        engine.getLoadWorker().stateProperty().addListener(
                (ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState) -> {
                    if (newState == Worker.State.SUCCEEDED) {
                        window = (JSObject) engine.executeScript("window");
                        window.setMember("text_code",text_code);
                    }
                }
        );

        engine.load(url);
        AnchorPane.setTopAnchor(view, 0.0);
        AnchorPane.setBottomAnchor(view, 0.0);
        AnchorPane.setLeftAnchor(view, 0.0);
        AnchorPane.setRightAnchor(view, 0.0);
        getChildren().add(view);

        view.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
            log.info("event.getCode:" + event.getCode());
            if (event.isControlDown() && event.getCode() == KeyCode.C) {
                event.consume();
                JSObject editor = (JSObject) engine.executeScript("window");
                //获取所选文本
                String text= editor.call("getSelected").toString();
                ClipboardUtils.setString(text);
            }
            if (event.isControlDown() && event.getCode() == KeyCode.X) {
                event.consume();
                JSObject editor = (JSObject) engine.executeScript("window");
                //获取所选文本
                String text= editor.call("getSelected").toString();
                ClipboardUtils.setString(text);
                //删除所选文本
                editor.call("removeSelectText"); // 删除选中的内容
            }


            if (event.isControlDown() && event.getCode() == KeyCode.S) {//保存
                event.consume();
                if (file != null){
                    try {
                        FileWriter writer = new FileWriter(file);
                        writer.write(text_code.getValue());
                        writer.flush();
                        writer.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }else {
                    //
                }
                AlertUtils.alert_warning("保存成功!");
            }

            if (event.isControlDown() && event.getCode() == KeyCode.DIVIDE) {//注释
                event.consume();
                window.call("commentLine");
            }

            if (event.isControlDown() && event.getCode() == KeyCode.O) {
                event.consume();
                //打开文件
                Stage stage = new Stage();
                FileChooser dc = new FileChooser();
                dc.setTitle("文件选择");
                dc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("文件类型", "*.java", "*.go", "*.txt", "*.json", "*.sql"));
                File file = dc.showOpenDialog(stage);
                String file_content = null;
                try {
                    file_content = Files.readString(file.toPath(), StandardCharsets.UTF_8);
                } catch (IOException e) {
                    try {
                        file_content = Files.readString(file.toPath(), Charset.forName("GBK"));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                this.file = file;
                JSObject editor = (JSObject) engine.executeScript("window");
                editor.call("setValue",file_content);
            }

        });
    }

    public static String getText() {
        return """
                package com.zhangmeng.tools.editors.monaco;
                                
                import com.zhangmeng.tools.utils.AlertUtils;
                import javafx.scene.input.KeyCode;
                import javafx.scene.input.KeyEvent;
                import javafx.scene.layout.AnchorPane;
                import javafx.scene.web.WebEngine;
                import javafx.scene.web.WebView;
                import javafx.stage.FileChooser;
                import javafx.stage.Stage;
                                
                import java.io.File;
                import java.io.FileWriter;
                import java.io.IOException;
                import java.nio.charset.Charset;
                import java.nio.charset.StandardCharsets;
                import java.nio.file.Files;
                                
                public class MonacoWebView extends AnchorPane {
                   \s
                    private File file;
                                
                    private WebView view = new WebView();
                                
                    public void init(){
                 \s
                        WebEngine engine = view.getEngine();
                                
                        String url = this.getClass().getResource("/static/editors/index2.html").toExternalForm();
                        engine.load(url);
                        AnchorPane.setTopAnchor(view,0.0);
                        AnchorPane.setBottomAnchor(view,0.0);
                        AnchorPane.setLeftAnchor(view,0.0);
                        AnchorPane.setRightAnchor(view,0.0);
                        getChildren().add(view);
                                
                        view.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
                            if (event.isControlDown() && event.getCode() == KeyCode.S){//保存
                                event.consume();
                                AlertUtils.alert_warning("保存成功!");
                            }
                                
                            if (event.isControlDown() && event.getCode() == KeyCode.O){
                                event.consume();
                                //打开文件
                                Stage stage = new Stage();
                                FileChooser dc = new FileChooser();
                                dc.setTitle("文件选择");
                                dc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("文件类型", "*.java", "*.go", "*.txt", "*.json", "*.sql"));
                                File file = dc.showOpenDialog(stage);
                                String file_content = null;
                                try {
                                    file_content = Files.readString(file.toPath(), StandardCharsets.UTF_8);
                                } catch (IOException e) {
                                    try {
                                        file_content = Files.readString(file.toPath(), Charset.forName("GBK"));
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                                this.file = file;
                                engine.executeScript("setValue('" + getText() +"')");
                            }
                                
                        });
                    }
                   \s
                    public static String getText(){
                        return ""\"
                                ""\";
                    }
                }
                                
                """;
    }
}
